package com.gf.controller;

import com.gf.client.AccountClient;
import com.gf.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RequestMapping("/api/order")
@RestController
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class OrderController {

    private final OrderService orderService;

    private final AccountClient accountClient;

    @GetMapping(value = "/debit")
    public void debit(@RequestParam String userId, @RequestParam String commodityCode, @RequestParam Integer count) {
        System.out.println("order XID " + RootContext.getXID());
        orderService.create(userId, commodityCode, count);
    }

    /**
     * 测试起点：http://127.0.0.1:8082/api/order/a2b?userId=1002&orderMoney=1
     * @param userId
     * @param orderMoney
     */
    @GetMapping(value = "/a2b")
    @GlobalTransactional(rollbackFor = Exception.class)
    public void a2b(@RequestParam String userId , @RequestParam BigDecimal orderMoney) {
        System.out.println("order XID " + RootContext.getXID());
        accountClient.debit(userId, orderMoney);
    }


    /**
     * 测试起点：http://127.0.0.1:8082/api/order/order2AccSub?userId=1002&orderMoney=1
     * @param userId
     * @param orderMoney
     */
    @GetMapping(value = "/order2AccSub")
    @GlobalTransactional(rollbackFor = Exception.class)
    public void order2AccSub(@RequestParam String userId , @RequestParam BigDecimal orderMoney) {
        System.out.println("order XID " + RootContext.getXID());
        accountClient.order2Acc(userId, orderMoney);
        throw new RuntimeException("11211");
    }

}
